<template>
    <view class="container">
        <u-navbar 
            leftText="实名认证"
             @leftClick="appFinish"  
			leftIconColor="#1D2129"
            bgColor="transparent">
        </u-navbar>
        <view class="form_container">
			<view class="notice_container" v-if="![AuthStatus.NotAuth].includes(status)">
				<view class="status" :class="statusClass">{{ statusMessage }}</view>
				<view class="note" v-html="noteMessage"></view>
			</view>
			<u-tabs v-if="[AuthStatus.NotAuth, AuthStatus.Fail].includes(status)" :list="tabs" lineWidth="60" lineColor="#295EFF" 
			:activeStyle="activeStyle" :inactiveStyle="inactiveStyle" 
			:current="currentTab" :itemStyle="itemStyle"  @change="changeTab"></u-tabs>
            <u-form ref="form" labelPosition="left" :rules="rules" :model="formData" labelWidth="auto" :labelStyle="labelStyle" >
                <template v-if="currentTab == 0">
                	<u-form-item label="企业名称"  prop="companyName" key="companyName" required >
                	    <u--input v-model="formData.companyName" placeholder="请输入企业名称" border="none" inputAlign="right" disabledColor="transparent" :disabled="isEnter"></u--input>
                	</u-form-item>
                	<view class="divider"></view>
                	<u-form-item label="统一社会信用代码"  prop="code" key="code" required >
                	    <u--input v-model="formData.code" placeholder="请输入统一社会信用代码" border="none" inputAlign="right" disabledColor="transparent" :disabled="isEnter"></u--input>
                	</u-form-item>
                	<view class="divider"></view>
                	<u-form-item label="营业执照"  prop="authFile" key="authFile" required labelPosition="top">
                		<view class="upload_wapper">
                			<view class="upload_content" v-if="[AuthStatus.NotAuth, AuthStatus.Fail].includes(status)">
                				<view class="upload_reasons">
                				    常见认证失败原因:
                				    <text>1、营业执照文字模糊，无法辨认；</text>
                				    <text>2、营业执照号码或文字有遮挡；</text>
                				    <text>3、营业执照已过期；</text>
                				    <text>4、上传的营业执照非扫描件</text>
                				</view>
                				<view class="upload_container" @click="uploadLicense">
                				    <img v-if="formData.authFile" :src="formData.authFile" mode="aspectFill"></img>
                				    <view v-else class="upload_placeholder"></view>
                				</view>
                			</view>
							<view class="upload_content" v-else>
								<view class="img_container">
								    <img v-if="formData.authFile" :src="formData.authFile" @click="previewImg(formData.authFile)"></img>
								</view>
							</view>
                			<view class="check_example" v-if="[AuthStatus.NotAuth, AuthStatus.Fail].includes(status)">
                				<text @click="show = true">查看示例</text>
                			</view>
                		</view>
                	</u-form-item>
                	<view class="divider"></view>
                	<u-form-item label="其他资料" labelPosition="top" class="custom_item">
                	   <view class="other_info">
						   <u-link class="files" v-if="formData.otherFile" :href="formData.otherFile" :text="formData.otherFileName"></u-link>
                		   <view v-if="[AuthStatus.NotAuth, AuthStatus.Fail].includes(status)" class="custom_btn" @click="handleOtherFiles">
                				<image src="@/static/image/uploadIcon.png"></image>
                				点击上传
                			</view>
                			<view class="tips">支持格式: .png .jpg .pdf .zip</view>
                	    </view>
                	</u-form-item>
                </template>
				<template v-if="currentTab == 1">
					<u-form-item label="姓名" prop="name" key="name" required>
					    <u--input v-model="formData.name" placeholder="请输入姓名" border="none" inputAlign="right" disabledColor="transparent" :disabled="isEnter"></u--input>
					</u-form-item>
					<view class="divider"></view>
					<u-form-item label="身份证号"  prop="idCard" key="idCard" required>
					    <u--input v-model="formData.idCard" placeholder="请输入身份证号" border="none" inputAlign="right" disabledColor="transparent" :disabled="isEnter"></u--input>
					</u-form-item>
				</template>
            </u-form>
        </view>
        <view class="footer" v-if="[AuthStatus.NotAuth, AuthStatus.Fail].includes(status)">
            <u-checkbox-group v-model="isAgree">
                <u-checkbox :value="true" />
            </u-checkbox-group>
			<view class="agreement"> 我已阅读并同意<text @click="viewAgreement">《认证说明》</text></view>
            <u-button type="primary" shape="circle" @click="submitForm">{{ submitBtnName }}</u-button>
        </view>
		<u-modal :show="show" :showConfirmButton="false" :closeOnClickOverlay="true" @close="show = false">
			<view class="slot-content">
				<view class="modal_header">
					<text>示例</text>
					<img src="@/static/image/close.png" class="modal_close" @click="show = false" />
				</view>
				<view class="modal_body">
					<img src="@/static/image/example.png" />
					<view class="modal_bottom_des">支持JPG/JPEG/PNG格式，大小不超过2M</view>
				</view>
			</view>
		</u-modal>
		<u-modal :show="showQrCode" :showConfirmButton="false" :closeOnClickOverlay="true" @close="showQrCode = false">
			<view class="slot-content">
				<view class="modal_header">
					<text>请用支付宝扫描</text>
					<img src="@/static/image/close.png" class="modal_close" @click="showQrCode = false" />
				</view>
				<view class="modal_body" @longpress="onLongpress">
					<uqrcode ref="qrcode" canvas-id="qrcode" :value="certifyUrl" :options="{ margin: 10 }"></uqrcode>
				</view>
			</view>
		</u-modal>
    </view>
</template>

<script>
import { txCosUpload } from '@/utils/txCosUpload'
const AuthStatus = {
  NotAuth: 0,
  Wait: 1,
  Success: 2,
  Fail: 3,
};
const AuthType = {
	Single: 1,
	Company: 2
}
export default {
    data() {
        return {
			AuthStatus, // 权限状态
            tabs: [
                { name: '企业认证' },
                { name: '个人认证' }
            ],
			show:false,                 // 示例弹框
			isEnter: false,             // 是否需要编辑表单
			currentTab: 0,              // 当前tab页
            authType: AuthType.Company, // 认证类型
			isAgree: [],                // 是否勾选
			status: AuthStatus.NotAuth, // 当前认证状态
			submitBtnName: '提交认证',   // 提交按钮名称
			showQrCode: false,          // 二维码弹框
			certifyUrl: '',             // 二维码链接
			labelStyle: {
				// letterSpacing: '1px',
				marginLeft: '10px',
			},
			activeStyle: {
				color: '#295FFF',
				fontWeight: 500,
			},
			inactiveStyle: {
				color: '#8F969E',
				fontWeight: 400,
			},
			itemStyle: 'padding-left: 20px; padding-right: 20px; height: 46px;',
			formData: {
				companyName: '',  // 企业名称
				code: '',         // 统一社会信用代码
				authFile: '',     // 营业执照
				otherFile: '',    // 其他资料
				otherFileName: '',// 其他资料名称
				name: '',         // 个人姓名
				idCard: ''        // 身份证号
			  },
            rules: {
                companyName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
                code: [{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }],
                authFile: [{ required: true, message: '请上传营业执照', trigger: 'change' }],
				name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
				idCard: [
					{ required: true, message: '请输入身份证号', trigger: 'blur' },
					{
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// uni.$u.test.idCard()就是返回true或者false的
							return uni.$u.test.idCard(value);
						},
						message: '身份证号格式不正确',
						// 触发器可以同时用blur和change
						trigger: ['change','blur'],
					}
				],
            }
        };
    },
	computed: {
		statusMessage() {
			switch (this.status) {
				case AuthStatus.NotAuth:
					return '您的帐号还未实名认证，请尽快完成认证。';
				case AuthStatus.Success:
					return '实名认证成功。';
				case AuthStatus.Wait:
					return '实名认证审核中，请耐心等待。';
				case AuthStatus.Fail:
					return '实名认证未未通过，请重新提交...';
				default:
					return '';
			}
		},
		statusClass() {
			switch (this.status) {
				case AuthStatus.NotAuth:
				case AuthStatus.Fail:
					return 'status-failed';
				case AuthStatus.Success:
					return 'status-success';
				case AuthStatus.Wait:
					return 'status-pending';
				default:
					return '';
			}
		},
		 noteMessage() {
			switch (this.status) {
				case AuthStatus.NotAuth:
					return '即可恢复直播功能正常使用。主体信息不支持修改，请确认后再提交';
				case AuthStatus.Success:
					return `认证主题不支持修改，如有疑问请联系客服邮箱：<text style="color: #295FFF">vlivekf@vlebo.cn</text>`;
				case AuthStatus.Wait:
					return `完成认证后不支持修改，如有疑问请联系客服邮箱：<text style="color: #295FFF">vlivekf@vlebo.cn</text>`;
				case AuthStatus.Fail:
					return `如有疑问请联系客服：<text style="color: #295FFF">400-625-68888</text>`;
				default:
					return '';
			}
		},
	},
	onLoad() {
		// 获取认证信息
		this.getAuthInfo();
	},
	onPullDownRefresh() {
		this.getAuthInfo()
	},
    methods: {
		previewImg(img){
			uni.previewImage({
				current: 0,
				urls: [img]
			});
		},
		appFinish() {
			this.$utils.appFinish(this)
		},
        goBack() {
            uni.navigateBack();
        },
        changeTab(item) {
            this.currentTab = item.index;
			this.submitBtnName = item.index === 0 ? '提交认证' : '支付宝扫码'
        },
		uploadLicense(){
			const vm = this
			this.$utils.androidAlbum(this)
			uni.chooseImage({
			    count: 1,
			    sizeType: ['original', 'compressed'],
			    sourceType: ['album', 'camera'],
			    success: async (res1) => {
					const file = res1.tempFiles[0];
					const params = {
						scene: 'real_auth'
					}
					txCosUpload(file, params, (progressData) => {
						// 实现进度条，目前没用到
						console.log(123,Math.round(progressData.percent * 100))
					},).then(res => {
						vm.formData.authFile = res.fileUrl
					})
			    }
			});
			
		},
        
        handleOtherFiles() {
            const vm = this
			this.$utils.androidAlbum(this)
            uni.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: async (res1) => {
            		const file = res1.tempFiles[0];
					const params = {
						scene: 'real_auth'
					}
            		txCosUpload(file,params,(progressData) => {
            			// 实现进度条，目前没用到
            		},).then(res => {
            			vm.formData.otherFile = res.fileUrl
						vm.formData.otherFileName = file.name
            		})
                }
            });
        },
        viewAgreement() {
            uni.navigateTo({
                url: '/pages/certification/description'
            });
        },
		// 获取认证信息
		async getAuthInfo() {
				let orgId = await this.$utils.getOrgId(this)
			  const params = {
				  orgId: orgId,
			  }
			  const res = await this.$request(this.$Api.getAuthInfo, params, "get")
		      const {
		        identity,
		        name,
		        status,
		        type,
		        errorMsg,
				licenseFile,
				descriptionFile,
				descriptionFileName,
		      } = res.data.data;
		      if (!type || type === 2) {
				   this.currentTab = 0
				   this.submitBtnName = '提交认证'
			  } else {
				  this.currentTab = 1,
				  this.submitBtnName = '支付宝扫码'
			  }
			  // 当前认证状态
			  this.status = status
			  // 未认证、认证失败才能编辑
			  this.isEnter = [AuthStatus.Wait, AuthStatus.Success].includes(status)
		      // 认证状态
		      if (status === AuthStatus.Success) {
		        if (type === AuthType.Single) {
				  this.formData.name = name
				  this.formData.idCard = identity
		        } else {
				  this.formData.companyName = name
				  this.formData.code = identity
				  this.formData.authFile = licenseFile
				  this.formData.otherFile = descriptionFile
				  this.formData.otherFileName = descriptionFileName
		        }
		      } else if (status === AuthStatus.Wait) {
		        this.formData.companyName = name
		        this.formData.code = identity
		        this.formData.authFile = licenseFile
		        this.formData.otherFile = descriptionFile
		        this.formData.otherFileName = descriptionFileName
		      } else if (status === AuthStatus.Fail) {
		        if (type === AuthType.Single) {
					this.formData.name = name
					this.formData.idCard = identity
		        } else {
		          this.formData.companyName = name
		          this.formData.code = identity
		          this.formData.authFile = licenseFile
		          this.formData.otherFile = descriptionFile
		          this.formData.otherFileName = descriptionFileName
		        }
		      }
			  uni.stopPullDownRefresh()
		    },
        async submitForm() {
			let orgId = await this.$utils.getOrgId(this)
            this.$refs.form.validate().then( async (valid) => {
                if (valid) {
					if (!this.isAgree.length) {
						return uni.showToast({
							title:'请先阅读并同意《认证说明》',
							icon: 'none',
							duration: 2000
						})
					}
					// 判断企业认证还是个人认证
					let params
					const { companyName,code,authFile,otherFile,otherFileName,name,idCard } = this.formData
					if (this.currentTab === 0) {
						params = {
							type: AuthType.Company,
							orgId: orgId,
							name: companyName,
							identity: code,
							license: authFile,
							description: otherFile,
							descriptionName: otherFileName
						}
					} else{
						params = {
							type: AuthType.Single,
							orgId: orgId,
							name: name,
							identity: idCard
						}
					}
					const { data } = await this.$request(this.$Api.submitAuthInfo, params, 'post')
					// 企业认证成功 
					if (this.currentTab === 0) {
						if (data.data.ok) {
							uni.showToast({
								title: '认证信息提交成功，请等待审核',
								icon: 'none',
								duration: 3000
							})
						}
						// 刷新认证信息
						this.getAuthInfo()
					} else {   // 个人认证需要扫描二维码
						this.certifyUrl = data.data.certifyUrl;
						this.showQrCode = true
					}
                }
            }).catch((e)=>{});
        },
		// 长按保存二维码图片
		onLongpress() {
			//#ifdef H5
			this.$refs.qrcode.toTempFilePath({
				success: res => {
					console.log(111, res);
					const aEle = document.createElement('a');
					aEle.download = 'uQRCode'; // 设置下载的文件名，默认是'下载'
					aEle.href = res.tempFilePath;
					document.body.appendChild(aEle);
					aEle.click();
					aEle.remove(); // 下载之后把创建的元素删除
				}
			});
			//#endif
			// #ifdef APP-PLUS
			this.$refs.qrcode.toTempFilePath({
				success: res => {
					console.log(222, res);
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: () => {
							uni.hideLoading();
							uni.showToast({
								title: "图片已保存"
							});
						},
						fail: () => {
							uni.hideLoading();
							uni.showToast({
								icon: 'none',
								title: "图片保存失败"
							});
						}
					});
				}
			});
			// #endif
		},

    }
};
</script>

<style lang="scss" scoped>
.container {
    position: relative;
    height: 100vh;
	overflow-y: hidden;
    background: url('@/static/image/bg.png') no-repeat center center;
    background-size: cover;
	padding-top: 98rpx;
	box-sizing: border-box;
	::v-deep .u-navbar__content__left__text{
		font-weight: 500;
		font-size: 32rpx;
	}
	.form_container {
	    background-color: #ffffff;
	    margin:0 32rpx;
		// margin-top: 96rpx;
	    border-radius: 16rpx;
		padding-top: 32rpx;
		.notice_container {
			margin:0 28rpx;
			padding: 20rpx;
			background: #F7FAFF;
			border-radius: 14rpx;
			.status{
				font-weight: 500;
				font-size: 32rpx;
				margin-bottom: 10rpx;
			}
			.status-success {
				color: #00C795;
			}
			.status-pending {
				color: #FF8059;
			}
			.status-failed {
				color: #FF5A5F;
			}
			.note{
				font-weight: 400;
				font-size: 28rpx;
				color: #8C8C8C;
				margin-bottom: 10rpx;
				line-height: 1.8;
			}
		}
		.divider{
			border-bottom: 1rpx solid #E3E8EE;
			margin: 30rpx 0;
		}
	
		.u-form{
			 padding: 40rpx;
			 ::v-deep .u-form-item__body{
				 padding: 10rpx 0;
			 }
			 ::v-deep .u-form-item__body__left__content__required{
			 	left: -1px;
			 }
		}
		::v-deep .u-tabs__wrapper__nav{
			border-bottom: 2rpx solid #E3E8EE;
			.u-tabs__wrapper__nav__line{
				bottom: 0;
			}
		}
		.custom_item{
			::v-deep .u-form-item__body__left__content__label{
				margin-left: 0 !important;
			}
		}
		.upload_wapper{
			width: 100%;
			.upload_content{
				display: flex;
				justify-content: space-between;
				width:100% ;
				margin: 10rpx 0;
				.upload_container {
					display: flex;
					align-items: center;
					justify-content: center;
					background: #F6F9FF;
					border-radius: 16rpx;
					width: 274rpx;
					height: 215rpx;
					overflow: hidden;
					position: relative;
					img{
						max-height: 100%;
						max-width: 100%;
					}
					.upload_placeholder {
						width: 100%;
						height: 100%;
						background:url('@/static/image/uploadBg.png') no-repeat center center;
						background-size: cover;    
					}
				}
				.upload_reasons {
					margin-top: 20rpx;
					font-size: 20rpx;
					color: #C8C9CC;
					text {
						display: block;
						margin-top: 10rpx;
					}
				}
				.img_container{
					flex: 1;
					height: 392rpx;
					width: 100%;
					display: flex;
					justify-content: center;
					align-items: center;
					background: #F6F9FF;
					border-radius: 16rpx;
					img{
						max-width: 100%;
						max-height: 100%;
					}
				}
			}
			.check_example {
				width: 100%;
				text-align: right;
				font-size: 24rpx;
				color: #295EFF;
				margin-top: 20rpx;
			}
		}
		
		.other_info {
			margin-top: 32rpx;
			.files{
				margin-bottom: 16rpx;
			}
			.tips{
				margin-bottom: 16rpx;
				font-weight: 400;
				font-size: 24rpx;
				color: #8F969E;
			}
		}
	}
	.custom_btn{
		display: flex;
		justify-content: center;
		align-items: center;
		width: fit-content;
		padding: 14rpx 32rpx;
		text-align: center;
		border: 2rpx solid #295EFF;
		border-radius: 8rpx;
		color: #295EFF;
		font-size: 28rpx;
		font-weight: 400;
		margin-bottom: 16rpx;
		image{
			width: 24rpx;
			height: 24rpx;
			margin-right: 12rpx;
		}
	}
	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 166rpx;
		box-sizing: border-box;
	    padding: 20rpx 40rpx 66rpx 40rpx;
	    background: #FFFFFF;
		box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(210,210,210,0.5);
	    display: flex;
	    align-items: center;
		.agreement {
			white-space: nowrap;
			font-size: 24rpx;
			color: #464C5B;
			text{
				color:#295EFF;
			}
		}
	}
	::v-deep .u-modal__content{
		padding-top: 36rpx !important;
		padding-bottom: 36rpx;
	}
	.slot-content{
		width: 100%;
	}
	.modal_header{
		position: relative;
		color: #1D2129;
		text-align: center;
		font-weight: 400;
		font-size: 34rpx;
		width: 100%;
		.modal_close{
			position: absolute;
			right: 0;
			top: 0;
			width: 42rpx;
			height: 42rpx;
		}
	}
	.modal_body {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		img{
			width: 60%;
			margin: 30rpx 0;
		}
		.modal_bottom_des {
			font-weight: 400;
			font-size: 24rpx;
			color: #8C8C8C;
		}
	}
}
</style>
